#include "VertexColorRender.h"
#include "GLFW/glfw3.h"

namespace Sivin {
  VertexColorRender::VertexColorRender() {
    mShader = std::make_unique<Shader>("./../shader/vertex_color/vert.vs", "./../shader/vertex_color/frag.fs");
    mVertexData = {
        0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f,  // 右上
        -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // 左上
        -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f,// 左下
        0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f};// 右下

    mElementIndexArray = {
        0, 1, 2, // 第一个三角形
        0, 2, 3};// 第二个三角形
  }

  VertexColorRender::~VertexColorRender() {
  }

  void VertexColorRender::onGLInit() {

    mShader->init();

    glGenVertexArrays(1, &mVAO);

    GLuint vbo, ebo;
    glGenBuffers(1, &vbo);
    glGenBuffers(1, &ebo);

    glBindVertexArray(mVAO);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * mVertexData.size(), mVertexData.data(), GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * mElementIndexArray.size(), mElementIndexArray.data(), GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void *) 0);

    //开启一个顶点属性后，必须对该顶点属性指定如何解析顶点数据
    //否则程序crash
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void *) (3 * sizeof(float)));

    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  }

  void VertexColorRender::onRender() {
    mShader->start();

    glBindVertexArray(mVAO);

    // GLfloat red = sin(glfwGetTime()) * 0.5 + 0.5;
    // glUniform4f(mInColorLocation, red, 0.3f, 0.6f, 1.0f);
    glDrawElements(GL_TRIANGLES, mElementIndexArray.size(), GL_UNSIGNED_INT, (void *) 0);
  }


}// namespace Sivin